package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os/exec"

	"golang.org/x/text/encoding/simplifiedchinese"
)

func main() {
	log.Println("Hello world")

	cmd := exec.Command("c:\\Program Files (x86)\\FTDI\\FT_Prog\\FT_Prog-CmdLine.exe", "scan")
	var stdout io.ReadCloser
	var err error
	if stdout, err = cmd.StdoutPipe(); err != nil {
		log.Fatal(err)
	}
	defer stdout.Close()

	go stdout_scan(&stdout)

	if err := cmd.Run(); err != nil {
		log.Println(err)
	}

	// var opBytes []byte

	// if opBytes, err = ioutil.ReadAll(stdout); err != nil {
	// 	log.Println(err)
	// } else {
	// 	log.Println(string(opBytes))
	// }

	// if i := strings.Index(string(opBytes), "No devices found!"); i != -1 {
	// 	log.Println(string(opBytes[i:]))
	// }

	var str string
	for {
		fmt.Scanf("%1s", &str)
		if str == "\r\n" || str == "\n\r" || str == "\r" || str == "\n" {
			return
		} else {
			log.Println(str)
		}
	}
}

func stdout_scan(r *io.ReadCloser) {
	scanner := bufio.NewScanner(*r)
	for scanner.Scan() {
		data, err := simplifiedchinese.GB18030.NewDecoder().Bytes(scanner.Bytes())
		if err != nil {
			log.Println("transfer error with bytes:", scanner.Bytes())
			continue
		}
		log.Println(string(data))
	}
	defer (*r).Close()
}
